<template>
  <div class="main">
    <el-table
      :data="list"
      v-loading="listLoading"
      element-loading-text="给我一点时间"
      border
      highlight-current-row
    >
      <el-table-column
        align="center"
        label="会员专题名称"
        prop="name"
      ></el-table-column>
      <el-table-column
        align="center"
        label="主标题"
        prop="title"
      ></el-table-column>
      <el-table-column
        align="center"
        label="达到多钱，可以升级"
        prop="money"
      ></el-table-column>
      <el-table-column align="center" label="礼包类型" prop="memberType">
        <template slot-scope="scope">
          <span v-if="scope.row.memberType === 1">VIP礼包</span>
          <span v-if="scope.row.memberType === 2">钻石礼包</span>
          <span v-if="scope.row.memberType === 3">38元礼包</span>
          <span v-if="scope.row.memberType === 4">29.9元礼包</span>
          <span v-if="scope.row.memberType === 5">VIP礼包</span>
          <span v-if="scope.row.memberType === 6">钻石礼包</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        v-if="rightsButtons['edit'] || rightsButtons['goods']"
      >
        <template slot-scope="scope">
          <el-button
            v-if="rightsButtons['edit']"
            type="primary"
            size="mini"
            @click="showEdit(scope.row)"
            >编辑</el-button
          >
          <router-link
            v-if="rightsButtons['goods']"
            :to="{
              name: 'upgradeMakeMoneyMemberGoods',
              params: { id: scope.row.id }
            }"
          >
            <el-button type="primary" plain size="mini">商品管理</el-button>
          </router-link>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container" v-if="listTotal > 0">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.pageIndex"
        :page-size="listQuery.pageSize"
        :total="listTotal"
        layout="total, prev, pager, next, jumper"
      ></el-pagination>
    </div>

    <el-dialog :title="form.id ? '编辑' : '新建'" :visible.sync="showEditPop">
      <el-form
        :model="form"
        :rules="formRules"
        size="medium"
        ref="form"
        label-width="120px"
      >
        <el-form-item label="会员礼包名称:" prop="name">
          <el-input
            v-model="form.name"
            placeholder="会员礼包名称"
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="主标题:" prop="title">
          <el-input
            v-model="form.title"
            placeholder="主标题"
            maxlength="100"
          ></el-input>
        </el-form-item>
        <el-form-item label="购买时效:">
          <div class="upTime">
            <div class="input_group">
              <el-form-item prop="upgradeTime">
                <el-input v-model="form.upgradeTime" maxlength="8"></el-input>
              </el-form-item>
              <el-select v-model="form.upgradeTimeUnit" placeholder="请选择">
                <el-option
                  v-for="item in daySelectList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <span>支持每人最多同时购买</span>
              <el-form-item prop="limitNum">
                <el-input v-model="form.limitNum" maxlength="8"></el-input>
              </el-form-item>
            </div>
            <div>次</div>
          </div>
        </el-form-item>
        <el-form-item label="购买条件:" prop="money">
          <el-input v-model="form.money" placeholder="金额（元）" maxlength="8">
            <template slot="prepend">满</template>
            <template slot="append">可升级</template>
          </el-input>
        </el-form-item>
        <el-form-item label="奖励内容:">
          <div>
            <span class="weight">奖励一: </span>
            <el-button type="primary" plain size="mini" @click="chooseCoupon(1)"
              >请选择优惠券</el-button
            >
            <span>每次购买会员，系统自动送优惠券，支持送多张给用户</span>
            <div class="coupon_div">
              <el-tag
                v-for="(coupons, index) in form.upgradeMakeMoneyCoupons"
                :key="index"
                closable
                :disable-transitions="false"
                @close="couponDelete(index, 'upgradeMakeMoneyCoupons')"
              >
                {{ coupons.name }}
              </el-tag>
            </div>
          </div>
          <div style="margin-top:20px;">
            <span class="weight">奖励二: </span>
            <el-button type="primary" plain size="mini" @click="chooseCoupon(2)"
              >请选择优惠券</el-button
            >
            <span>每次购买会员，系统自动送指定商品优惠券，支持10选一</span>
            <div class="coupon_div">
              <el-tag
                v-for="(coupons, index) in form.selectorCoupons"
                :key="index"
                closable
                :disable-transitions="false"
                @close="couponDelete(index, 'selectorCoupons')"
              >
                {{ coupons.name }}
              </el-tag>
            </div>
          </div>
          <div class="config" v-if="form.memberType == 6">
            <div class="config-item">
              <span class="weight">奖励三: </span>
              <span>每次购买会员后得</span>
              <el-form-item prop="upgradeGetCardNum" class="config-form-item">
                <el-input
                  v-model="form.upgradeGetCardNum"
                  maxlength="8"
                  style="width: 70px;"
                ></el-input>
              </el-form-item>
              <span>张VIP卡，</span>
              <el-form-item
                prop="upgradeGetCardExpire"
                class="config-form-item"
              >
                <el-input
                  v-model="form.upgradeGetCardExpire"
                  maxlength="5"
                  style="width: 70px;"
                ></el-input>
              </el-form-item>
              <span>天自动过期，好友领取后</span>
              <el-form-item prop="friendsReceiveTime" class="config-form-item">
                <el-input
                  v-model="form.friendsReceiveTime"
                  maxlength="8"
                  style="width: 70px;"
                ></el-input>
              </el-form-item>
              <el-form-item
                prop="friendsReceiveTimeUnit"
                class="config-form-item"
              >
                <el-select
                  v-model="form.friendsReceiveTimeUnit"
                  placeholder="请选择"
                  class="config-select"
                >
                  <el-option
                    v-for="item in daySelectList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <span>有效。</span>
            </div>
            <div class="config-item">
              <span class="weight">奖励四: </span>
              <span>每次购买会员后</span>
              <el-form-item prop="upgradeRewardExpire" class="config-form-item">
                <el-input
                  v-model="form.upgradeRewardExpire"
                  maxlength="8"
                  style="width: 70px;"
                />
              </el-form-item>
              <span>天，累积成功送出</span>
              <el-form-item
                prop="upgradeRewardCondition"
                class="config-form-item"
              >
                <el-input
                  v-model="form.upgradeRewardCondition"
                  maxlength="8"
                  style="width: 70px;"
                />
              </el-form-item>
              <span>张VIP卡，再得</span>
              <el-form-item
                prop="upgradeRewardCardNum"
                class="config-form-item"
              >
                <el-input
                  v-model="form.upgradeRewardCardNum"
                  maxlength="8"
                  style="width: 70px;"
                />
              </el-form-item>
              <span>张VIP卡，</span>
              <el-form-item
                prop="upgradeRewardCardExpire"
                class="config-form-item"
              >
                <el-input
                  v-model="form.upgradeRewardCardExpire"
                  maxlength="8"
                  style="width: 70px;"
                />
              </el-form-item>
              <span>天自动过期，好友领取后</span>
              <el-form-item
                prop="rewardFriendsReceiveTime"
                class="config-form-item"
              >
                <el-input
                  v-model="form.rewardFriendsReceiveTime"
                  maxlength="8"
                  style="width: 70px;"
                />
              </el-form-item>
              <el-form-item
                prop="rewardFriendsReceiveTimeUnit"
                class="config-form-item"
              >
                <el-select
                  v-model="form.rewardFriendsReceiveTimeUnit"
                  placeholder="请选择"
                  class="config-select"
                >
                  <el-option
                    v-for="item in daySelectList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <span>有效。</span>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="描述:" prop="desc">
          <el-input
            type="textarea"
            resize="none"
            v-model="form.desc"
            placeholder="描述"
            maxlength="300"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="save" :loading="btnLoading"
          >保存</el-button
        >
        <el-button @click="showEditPop = false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="form.id ? '编辑' : '新建'"
      :visible.sync="showEditPop_old"
    >
      <el-form
        :model="form"
        :rules="formRules"
        size="medium"
        ref="form"
        label-width="120px"
      >
        <el-form-item label="标题:" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="banner:" prop="banner">
          <el-upload
            class="avatar-uploader"
            accept="image/*"
            :action="upladUrl"
            name="file"
            :show-file-list="false"
            :on-success="uploadSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="form.banner" :src="form.banner" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="类型:" prop="type">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option :key="1" label="年会" :value="'1'"></el-option>
            <el-option :key="2" label="城市合伙人" :value="'2'"></el-option>
            <el-option :key="3" label="普通专题" :value="'3'"></el-option>
            <el-option :key="4" label="H5" :value="'4'"></el-option>
            <el-option :key="5" label="独立箱起" :value="'5'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型值:" prop="typeVal">
          <el-input v-model="form.typeVal"></el-input>
        </el-form-item>
        <el-form-item label="规则详情URL:" prop="detailUrl">
          <el-input v-model="form.detailUrl"></el-input>
        </el-form-item>
        <el-form-item label="简介:" prop="instruction">
          <el-input
            type="textarea"
            :rows="2"
            v-model="form.instruction"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序:" prop="sort">
          <el-input v-model="form.sort"></el-input>
        </el-form-item>
        <el-form-item label="是否启用:" prop="status">
          <el-switch
            v-model="form.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="save" :loading="btnLoading"
          >保存</el-button
        >
        <el-button @click="showEditPop_old = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { regexp } from '../../utils/tools'
let defaultForm = {
  // 奖励三
  upgradeGetCardNum: 1,
  upgradeGetCardExpire: 1,
  friendsReceiveTime: 1,
  friendsReceiveTimeUnit: 1,
  // 奖励四
  upgradeRewardExpire: 1,
  upgradeRewardCondition: 1,
  upgradeRewardCardNum: 1,
  upgradeRewardCardExpire: 1,
  rewardFriendsReceiveTime: 1,
  rewardFriendsReceiveTimeUnit: 1
}
let rule1 = [
  { required: true, message: '不能为空', trigger: 'blur' },
  {
    pattern: regexp.positiveInt,
    message: '必须为正整数',
    trigger: 'blur'
  }
]
let rule2 = [
  { required: true, message: '不能为空', trigger: 'blur' },
  {
    pattern: regexp.positiveInt,
    message: '必须为正整数',
    trigger: 'change'
  }
]
export default {
  name: 'upgradeMakeMoneyMember',
  data() {
    var valid_limitNum = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('购买次数不能小于0'))
      } else if (value == '') {
        callback(new Error('购买次数不能为空'))
      } else {
        callback()
      }
    }

    return {
      list: [],
      listQuery: {
        pageIndex: 1,
        pageSize: 20,
        isPage: 1
      },
      listTotal: 0,
      listLoading: false,
      form: {},
      formRules: {
        name: [{ required: true, message: '不能为空', trigger: 'change' }],
        upgradeTime: [
          { required: true, message: '升级时效有必填项', trigger: 'change' }
        ],
        upgradeTimeUnit: [
          { required: true, message: '升级时效有必填项', trigger: 'change' }
        ],
        title: [{ required: true, message: '不能为空', trigger: 'change' }],
        limitNum: [
          { required: true, validator: valid_limitNum, trigger: 'blur' }
        ],
        money: [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.money,
            message: '格式错误(至多保留两位小数)',
            trigger: 'change'
          }
        ],
        sort: [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.sort,
            message: '必须为1-999的正整数',
            trigger: 'change'
          }
        ],
        upgradeGetCardNum: rule1,
        upgradeGetCardExpire: rule1,
        friendsReceiveTime: rule1,
        friendsReceiveTimeUnit: rule2,
        upgradeRewardExpire: rule1,
        upgradeRewardCondition: rule1,
        upgradeRewardCardNum: rule1,
        upgradeRewardCardExpire: rule1,
        rewardFriendsReceiveTime: rule1,
        rewardFriendsReceiveTimeUnit: rule2
      },
      showEditPop: false,
      showEditPop_old: false,
      btnLoading: false,
      dayValue: 1,
      daySelectList: [
        {
          value: 1,
          label: '天'
        },
        {
          value: 2,
          label: '月'
        },
        {
          value: 3,
          label: '季'
        },
        {
          value: 4,
          label: '年'
        },
        {
          value: 5,
          label: '终身'
        }
      ],
      showMoreReward: false
    }
  },
  watch: {
    'form.money': {
      handler(newVal) {
        var n = Number(newVal)
        if (!isNaN(n)) {
          if (n >= 398) {
            this.showMoreReward = true
          } else {
            this.showMoreReward = false
          }
        } else {
          this.showMoreReward = false
        }
      },
      deep: true
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表
    getList() {
      this.request({
        url: '/bsnl-activity/upgradeMakeMoneyMember/list',
        method: 'get',
        params: this.listQuery
      })
        .then(({ data, totalCount }) => {
          this.list = data
          this.listTotal = totalCount
          this.listLoading = false
        })
        .catch(err => {
          this.list = []
          this.listTotal = 0
          this.listLoading = false
        })
    },
    showEdit(row) {
      this.request({
        url: '/bsnl-activity/upgradeMakeMoneyMember/details',
        method: 'get',
        params: { id: row.id }
      })
        .then(({ data }) => {
          this.form = data
          this.$nextTick(() => {
            this.$refs.form.clearValidate()
          })
          if (row.memberType == 3 || row.memberType == 4) {
            this.showEditPop_old = true
          } else {
            this.showEditPop = true
          }
          this.btnDisabled = false
        })
        .catch(err => {
          console.log(err)
        })
    },
    beforeUpload(file) {
      if (!/image/.test(file.type)) {
        this.$message.error('只能上传图片')
        return false
      }
      if (file.size > 1024 * 1024) {
        this.$message.error('图片不能大于1M')
        return false
      }
    },
    uploadSuccess(res) {
      this.form.banner = this.replaceImgUrl(res.filePath)
    },
    handleCurrentChange(val) {
      this.listQuery.pageIndex = val
      this.getList()
    },
    save() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return false
        }
        for (var i = 0; i < this.form.upgradeMakeMoneyCoupons.length; i++) {
          this.form.upgradeMakeMoneyCoupons[
            i
          ].upgradeMakeMoneyMemberId = this.form.id
        }
        let url = this.form.id
          ? '/bsnl-activity/upgradeMakeMoneyMember/update'
          : '/bsnl-activity/upgradeMakeMoneyMember/create'
        this.btnLoading = true
        this.request({
          url,
          method: 'post',
          data: this.form
        })
          .then(() => {
            this.btnLoading = false
            this.showEditPop = false
            this.showEditPop_old = false
            this.$message.success('保存成功')
            this.getList()
          })
          .catch(err => {
            console.log(err)
            this.btnLoading = false
          })
      })
    },
    couponDelete(index, type) {
      this.form[type].splice(index, 1)
    },
    chooseCoupon(type) {
      // 系统发放
      let receiveType = 2
      switch (type) {
        case 1:
          this.couponChoose(
            { validFlag: true, receiveType },
            this.form.upgradeMakeMoneyCoupons
          ).then(val => {
            this.form.upgradeMakeMoneyCoupons = val
          })
          break
        case 2:
          this.couponChoose(
            { validFlag: true, receiveType, useTypes: ["BY_CONDITION"] },
            this.form.selectorCoupons
          ).then(val => {
            this.form.selectorCoupons = val.slice(0, 10)
          })
          break
        default:
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.coupon_3_title {
  display: flex;
}
.upTime {
  display: flex;
  div {
    flex: 1;
  }
  .input_group {
    display: flex;
  }
}
.avatar-uploader {
  .el-upload {
    position: relative;
    width: 100px;
    height: 100px;
    line-height: 98px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    overflow: hidden;
    box-sizing: border-box;
  }
}
.coupon_div {
  border: 1px solid #dcdfe6;
  min-height: 100px;
  .el-tag {
    margin-left: 10px;
  }
}

.weight {
  font-weight: 600;
}
.config-form-item {
  display: inline-block;
}
.config {
  .config-item {
    margin-top: 20px;
  }
}
.config-select {
  width: 100px !important;
  margin-top: 10px;
}
</style>
